"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { useToast } from "@/components/ui/use-toast"
import { ArrowLeft, User, LogOut } from "lucide-react"
import { useAuth } from "@/lib/auth/auth-context"
import { 
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog"

export default function ProfilePage() {
  const router = useRouter()
  const { toast } = useToast()
  const { user, logout, isAuthenticated, isLoading } = useAuth()
  const [isUpdating, setIsUpdating] = useState(false)
  const [showLogoutDialog, setShowLogoutDialog] = useState(false)
  
  const [formData, setFormData] = useState({
    name: "",
    email: ""
  })

  // 当用户数据加载完成后，更新表单数据
  useEffect(() => {
    if (user) {
      setFormData({
        name: user.name,
        email: user.email
      })
    }
  }, [user])

  // 如果用户未登录且加载完成，重定向到登录页面
  useEffect(() => {
    if (!isLoading && !isAuthenticated) {
      router.push("/login")
    }
  }, [isLoading, isAuthenticated, router])

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({ ...prev, [name]: value }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsUpdating(true)
    
    try {
      // 模拟更新请求
      // 注意：这里只是前端模拟，后续需要替换为实际的API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 更新本地存储的用户数据
      if (user) {
        const updatedUser = {
          ...user,
          name: formData.name,
          email: formData.email
        }
        localStorage.setItem("user", JSON.stringify(updatedUser))
      }
      
      toast({
        title: "更新成功",
        description: "您的个人资料已更新",
      })
    } catch (error) {
      toast({
        title: "更新失败",
        description: "更新个人资料时出现问题，请重试",
        variant: "destructive",
      })
    } finally {
      setIsUpdating(false)
    }
  }

  // 处理退出登录
  const handleLogout = () => {
    logout()
    setShowLogoutDialog(false)
  }

  // 如果正在加载，显示加载状态
  if (isLoading) {
    return (
      <div className="min-h-screen bg-[#f9f8f6] flex items-center justify-center">
        <div className="flex items-center space-x-2">
          <div className="w-3 h-3 bg-emerald-400 rounded-full animate-bounce [animation-delay:-0.3s]"></div>
          <div className="w-3 h-3 bg-emerald-400 rounded-full animate-bounce [animation-delay:-0.15s]"></div>
          <div className="w-3 h-3 bg-emerald-400 rounded-full animate-bounce"></div>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-[#f9f8f6] flex flex-col">
      {/* Header */}
      <div className="bg-white border-b">
        <div className="max-w-3xl mx-auto px-4 py-3 flex items-center justify-between">
          <div className="flex items-center">
            <Button variant="ghost" size="icon" onClick={() => router.push("/")} className="mr-2">
              <ArrowLeft className="h-4 w-4" />
            </Button>
            <h1 className="text-lg font-medium">个人资料</h1>
          </div>
          
          {/* 退出登录按钮 - 直接点击退出 */}
          <Button variant="ghost" size="sm" className="text-red-500" onClick={logout}>
            <LogOut className="h-4 w-4 mr-2" />
            退出登录
          </Button>
        </div>
      </div>
      
      {/* Main Content */}
      <div className="flex-1 flex items-start justify-center p-4 pt-8">
        <div className="w-full max-w-md space-y-8">
          {/* 用户头像 */}
          <div className="flex flex-col items-center space-y-4">
            <div className="w-24 h-24 bg-emerald-100 rounded-full flex items-center justify-center">
              <User className="h-12 w-12 text-emerald-600" />
            </div>
            <h2 className="text-xl font-medium">{user?.name}</h2>
          </div>
          
          {/* 个人资料表单 */}
          <div className="bg-white rounded-xl shadow-sm p-6 border">
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="name">用户名</Label>
                <Input
                  id="name"
                  name="name"
                  value={formData.name}
                  onChange={handleChange}
                  required
                />
              </div>
              
              <div className="space-y-2">
                <Label htmlFor="email">邮箱</Label>
                <Input
                  id="email"
                  name="email"
                  type="email"
                  value={formData.email}
                  onChange={handleChange}
                  required
                />
              </div>
              
              <Button type="submit" className="w-full" disabled={isUpdating}>
                {isUpdating ? "更新中..." : "保存更改"}
              </Button>
            </form>
          </div>
          
          {/* 其他选项 */}
          <div className="bg-white rounded-xl shadow-sm p-6 border">
            <h3 className="text-lg font-medium mb-4">账号设置</h3>
            <div className="space-y-3">
              <Button variant="outline" className="w-full justify-start" onClick={() => router.push("/cabinet")}>
                我的酒柜
              </Button>
              <Button variant="outline" className="w-full justify-start" onClick={() => router.push("/change-password")}>
                修改密码
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
} 